package utils

import (
	"fmt"
	"github.com/golang-jwt/jwt/v4"
	"gorm-demo/global"
	"time"
)

var (
	USER_ID = "user_id"
)

func NewToken(userId int, expiration time.Duration) (string, error) {
	token := jwt.New(jwt.SigningMethodHS256)
	claims := token.Claims.(jwt.MapClaims)
	claims[USER_ID] = userId
	claims["exp"] = time.Now().Add(expiration).Unix()
	signedString, err := token.SignedString(global.TOKEN_SIGNING)
	if err != nil {
		return "", err
	}
	return signedString, nil
}
func GetUserId(token string) (int, error) {
	parseToken, err := ParseToken(token)
	if err != nil {
		return 0, err
	}
	claims, _ := parseToken.Claims.(jwt.MapClaims)
	return int(claims[USER_ID].(float64)), nil
}

// ParseToken 解析JWT Token
func ParseToken(tokenString string) (*jwt.Token, error) {
	parse, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return global.TOKEN_SIGNING, nil
	})
	return parse, err
}
func ValidateJwt(token string) (bool, error) {
	_, err := ParseToken(token)
	if err != nil {
		return false, err
	}
	return true, nil
}
